import Web3 from "web3";
var contract = null;
var web3 = null;
var myAddr = ''; //我的钱包地址
var toAddress = ''; //转账地址

// 正式
var contractDecimals = 18;
var contractAddress = '0x55d398326f99059ff775485246999027b3197955'; // 合约地址

// 签名
export function getSign(message, address) {
	return new Promise(function(resolve, reject) {
		web3 = new Web3(window.ethereum)
		web3.eth.personal.sign(web3.utils.utf8ToHex(message), address).then(res => {
			resolve(res)
		}).catch(error => {
			reject(error)
		})
	});
}

// 获取钱包地址
export function getWalletAddress() {
	return new Promise(function(resolve, reject) {
		web3 = new Web3(window.ethereum);
		window.ethereum.enable().then(function(accounts) {
			resolve(web3.utils.toChecksumAddress(accounts[0]))
		}).catch((reason) => {
			reject(reason)
		});
	});
}

// 获取钱包余额
export function getwalletBalance(myAddr, contractAddress, abi) {
	return new Promise(function(resolve, reject) {
		contract = new web3.eth.Contract(abi, contractAddress);
		contract.methods.balanceOf(myAddr).call().then((balance) => {
			resolve(balance)
		}).catch(error => {
			reject(error)
		})
	});
}

// 授权
export function startAuth(toAddress,num) {
	let str = num * Math.pow(10, 18);
	str += '';
	return new Promise(function(resolve, reject) {
		contract.methods.approve(toAddress, str).send({
			from: myAddr
		}).then(res => {
			resolve(res)
		}).catch(error => {
			reject(error)
		})
	});
}

// 转账
export function startTransfer(num, toAddress, myAddr) {
	return new Promise(function(resolve, reject) {
		let str = num * Math.pow(10, 18);
		str += '';
		contract.methods.transfer(toAddress, str).send({
			from: myAddr
		}).then(res => {
			resolve(res)
		}).catch(error => {
			reject(error)
		})
	});
}